package com.atwork.controller;

import com.atwork.model.normal.SysUser;
import com.atwork.model.vo.ShiroUser;
import com.atwork.utils.ServerResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @CreateBy: zhaojun
 * @CreateTime: 2018-08-04
 * @Desc: 登陆Controller
 */
@Controller
public class LoginController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //shiro session
    @Autowired
    private SessionDAO sessionDAO;

    /**
     * 空路径访问
     * @param model
     * @return
     */
    @RequestMapping(value = "/")
    public Object index1(ModelAndView model) {
        model.addObject("loginError", "");
        model.setViewName("login");
        return model;
    }

    /**
     * 主页访问
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/index")
    public Object index(HttpServletRequest request, ModelAndView model) {
        model.setViewName("index");
        model.addObject("loginName",getShiroUser().getLoginName());
        model.addObject("loginId",getShiroUser().getUserId());
        return model;
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public  Object login(@RequestParam("loginName")String loginName,@RequestParam("password")String password) {
        logger.info("请求登录");
        if(loginName == null || "".equals(loginName)){
            logger.info("请输入用户名");
            return ServerResponse.createByErrorMessage("请输入用户名");
        };
        if(password == null || "".equals(password)){
            logger.info("请输入密码");
            return ServerResponse.createByErrorMessage("请输入密码");
        };
        ShiroUser shiroUser = getShiroUser(loginName);
        logger.info(shiroUser.getUserName()+"登录系统");
        String remember = super.getPara("remember");
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
        if ("on".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }
        try {
            Collection<Session> activeSessions = sessionDAO.getActiveSessions();
            for (Session session:activeSessions){
                if(session.getAttribute("username") !=null&& !"".equals(session.getAttribute("username"))){
                    String username = session.getAttribute("username").toString();
                    if(loginName.equals(username)){
                        sessionDAO.delete(session);
                        session.removeAttribute("username");
                    }
                }
            }
            currentUser.login(token);
        } catch  ( UnknownAccountException uae ) {
            return ServerResponse.createByErrorMessage("帐号不存在");
        } catch  ( IncorrectCredentialsException ice ) {
            return ServerResponse.createByErrorMessage("用户名或密码错误");
        } catch  ( LockedAccountException lae ) {
            return ServerResponse.createByErrorMessage("帐号被禁用");
        } catch  ( ExcessiveAttemptsException eae ) {
            return ServerResponse.createByErrorMessage("登录失败次数过多");
        } catch ( AuthenticationException ae ) {
            return ServerResponse.createByErrorMessage("认证失败，请联系管理员");
        }
        super.getSession().setAttribute("loginName", shiroUser.getLoginName());
        currentUser.getSession().setAttribute("loginName", shiroUser.getLoginName());
        currentUser.getSession().setAttribute("userId", shiroUser.getUserId());
        currentUser.getSession().setAttribute("userName", shiroUser.getUserName());
        Map<String,Object> map = new HashMap<>();
        map.put("sessionId",currentUser.getSession().getId());
        map.put("code",200);
        map.put("msg","登录成功");
        return ServerResponse.createBySuccess(map);
    }
    @RequestMapping(value = "/loginOut",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object loginOut(ModelAndView model) {
        model.addObject("loginError", "");
        model.setViewName("login");
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return ServerResponse.createBySuccessMessage("退出系统");
    }
}
